/* eslint-disable react/destructuring-assignment */
/* eslint-disable prettier/prettier */
/* eslint-disable no-multiple-empty-lines */
import { random } from 'lodash';
import React from 'react';
import { View, StyleSheet, PanResponder, Dimensions, Animated, Image, Easing, AppState } from 'react-native';
// import Snow from './imgs/snow.png';
// import SantaClaus from './imgs/12.png';
// import Tree from './imgs/tree.png';
// import SnowMan from './imgs/snowMan.png';
import Res from '../../res';
const { height: deviceHeight, width: deviceWidth } = Dimensions.get('window');
const arr = [];
const snowNumber = 200;
const localX = [];
const randomSize = [];
for (var i = 0; i < snowNumber; i++) {
  arr.push(i);
  localX.push(Math.random() * (deviceWidth));
  randomSize.push(random(8, 20));
}

export default class DragSquare extends React.Component {
  constructor(props) {
    super(props);
    // this.state = {
    // 	fadeInOpacity: new Animated.Value(1)
    // };
    // this.animateSnowmanValue = new Animated.Value(0);
    this.animatedValue = [];
    this.fadeInOpacity = [];
    arr.forEach(value => {
      this.animatedValue[value] = new Animated.Value(0);
      // this.setState({
      //   fadeInOpacity[value] :new Animated.Value(1)
      // })
      this.fadeInOpacity[value] = new Animated.Value(1);
    });
    this.flage = false;
  }




  componentWillMount() {
    this._animatedValue = new Animated.ValueXY();
    this._value = { x: 0, y: 0 };
    this._animatedValue.addListener(value => (this._value = value));

    this._panResponder = PanResponder.create({
      // Ask to be the responder:
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
      onMoveShouldSetPanResponder: (evt, gestureState) => true,
      onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,

      onPanResponderGrant: (e, gestureState) => {
        this._animatedValue.setOffset({ x: this._value.x, y: this._value.y });
      },
      onPanResponderMove: Animated.event([
        null,
        { dx: this._animatedValue.x, dy: this._animatedValue.y },
      ]),
      onPanResponderRelease: () => {
        this._animatedValue.flattenOffset();
      },
    });
  }

  componentDidMount() {
    this.animateSnow();
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  // animateSnowMan() {
  //   this.animateSnowmanValue.setValue(0);
  //   Animated.timing(this.animateSnowmanValue, {
  //     toValue: 100,
  //     duration: 1000,
  //     easing: Easing.linear,
  //   }).start(() => this.animateSnowMan());
  // }

  _handleAppStateChange = (nextAppState) => {
    if (nextAppState != null && nextAppState === 'active') {
      // 如果是true ，表示从后台进入了前台 ，请求数据，刷新页面。或者做其他的逻辑

      if (this.flage) {
        // console.log('从后台进入前台');
        // 这里的逻辑表示 ，第一次进入前台的时候 ，不会进入这个判断语句中。
        // 因为初始化的时候是false ，当进入后台的时候 ，flag才是true ，
        // 当第二次进入前台的时候 ，这里就是true ，就走进来了。
        // 测试通过
        // alert("从后台进入前台");
        // 这个地方进行网络请求等其他逻辑。


      }
      this.flage = false;
    } else if (nextAppState != null && nextAppState === 'background') {
      this.flage = true;
    }
  }

  animateSnow() {
    arr.forEach(value => {
      this.animatedValue[value].setValue(0);
      this.fadeInOpacity[value].setValue(1);
    });
    const animations = arr.map((item, index) => {
      
      return Animated.parallel([
        Animated.timing(this.fadeInOpacity[index], {
          toValue: 0,
          duration: 5000,

        }),
        Animated.timing(this.animatedValue[item], {
          toValue: snowNumber,
          duration: 8000,
          easing: Easing.linear,
        }),
      ]);
    });
    Animated.stagger(300, animations).start(({ finished }) => {
      /* 动画完成的回调函数 */
      this.animateSnow();
    });

  }

  snowAnimate(item, i) {
    return {
      position: 'absolute',
      left: parseInt(localX[i], 10),
      top: this.animatedValue[item].interpolate({
        inputRange: [0, snowNumber],
        outputRange: [-100, deviceHeight - 100],
      }),
    };
  }



  render() {
    let interpolatedRotation = this._animatedValue.x.interpolate({
      inputRange: [0, deviceWidth / 2, deviceHeight / 2],
      outputRange: ['-360deg', '0deg', '360deg'],
    });

    const animations = arr.map((a, i) => {
      return (
        <Animated.View
          key={i}
          style={[styles.snowBox,
            this.snowAnimate(a, i),
            { opacity: this.fadeInOpacity[i] }
          ]}
        >
          <Image
            source={Res.snow1}
            style={[
              styles.snow,
              {
                width: randomSize[i],
                height: randomSize[i],
              },
            ]}
          />
        </Animated.View>
      );
    });

    return (
      <View style={styles.container}>
        
        <Animated.View
          style={[
            styles.box,
            {
              transform: [
                { translateX: this._animatedValue.x },
                { translateY: this._animatedValue.y },
                { rotate: interpolatedRotation },
              ],
            },
          ]}
          {...this._panResponder.panHandlers}
        >
          {/* <Image style={styles.image} source={Res.fanStrong} /> */}
        </Animated.View>
        {animations}
        {/* <Animated.View style={styles.tree}>
          <Image style={styles.image} source={Res.display} />
        </Animated.View>
        <Animated.View style={[styles.snowMan, animateSnowMan]}>
          <Image style={styles.image} source={Res.fanSleep} />
        </Animated.View> */}
        <View style={styles.topMask} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
  },
  box: {
    width: 50,
    height: 50,
  },
  snowBox: {
    width: 18,
    height: 18,
  },
  topMask: {
    position: 'absolute',
    width: '100%',
    height: 30,
    top: -100,
    backgroundColor: '#ffffff',
  },
  snow: {
    width: '100%',
    height: '100%',
  },
});